package cn.ittgh.controller.Files.Local;

import cn.ittgh.pojo.Commons.Result;
import cn.ittgh.pojo.Image.Image;
import cn.ittgh.service.Image.ImageService;
import cn.ittgh.utils.ThreadLocalUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.*;

@RestController
@RequestMapping("/files")
public class LocalFileController {

	@Value("${api.prefix}")
	private String prefix;
	@Value("${server.port}")
	private String servePort;
	@Value("${files.local.upload.path}")
	private String fileUploadPath;

	@Value("${server.ssl.protocol}")
	private String protocol;


	@Autowired
	private ImageService imageService;


	public LocalFileController() throws UnknownHostException {
	}

	@PostMapping("/upload")
	public <T> Result<T> upload(HttpServletRequest httpServletRequest, @RequestParam(value = "file") MultipartFile file) throws IOException {
		// 获取文件类型
		String contentType = file.getContentType();

		// 图片格式
		List<String> listType = new ArrayList<>();
		listType.add("image/png");
		listType.add("image/jpeg");
		listType.add("image/jpg");

		if (!listType.contains(contentType)) {
			return Result.error("上传文件格式不允许！");
		}
		// 获取输入流
		InputStream inputStream = file.getInputStream();
		// 生成uuid
		String uuid = UUID.randomUUID().toString();
		// 获取文件扩展名
		String fix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
		// 生成文件完整名称
		String fileName = uuid + fix;
		// 文件绝对路径
		String absolutePath = fileUploadPath + fileName;

		File folder = new File(fileUploadPath);
		// 生成文件目录
		if (!folder.exists()) {
			folder.mkdirs();
		}
		// 写入文件
		int len = 0;
		FileOutputStream fileOutputStream = new FileOutputStream(absolutePath);
		while ((len = inputStream.read()) != -1) {
			fileOutputStream.write(len);
		}
		fileOutputStream.close();
		inputStream.close();

		Map<String, String> fileMap = new HashMap<>();
		fileMap.put("fileId", file.getOriginalFilename());
		fileMap.put("fileName", file.getOriginalFilename());
		fileMap.put("fileOriName", file.getOriginalFilename());
		String httpType = Objects.equals(protocol, "TLS") ? "https" : "http";
		fileMap.put("filePath", httpType + "://" + httpServletRequest.getServerName() + ":" + servePort + prefix + "/files/views?fileName=" + fileName);

		try {
			imageService.add(new Image(UUID.randomUUID().toString(), ThreadLocalUtil.getUserId(), file.getOriginalFilename(), fileMap.get("filePath")));
			return (Result<T>) Result.success(fileMap);
		} catch (Exception ignored) {
			return Result.error("上传图片失败");
		}

	}

	@GetMapping("/views")
	public void views(@RequestParam String fileName, HttpServletResponse response) throws IOException {
		// 截取名称
		String[] split = fileName.split("/");
		String name = split[split.length - 1];

		File file = new File(fileUploadPath + name);
		// 设置输出流格式
		ServletOutputStream outputStream = response.getOutputStream();
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));

		// 任意类型的二进制流
		response.setContentType("application/octet-steam");
		// 读取字节流
		outputStream.write(FileUtil.readAsByteArray(file));
		outputStream.close();
	}
}
